<?php

namespace Admin\Controller;
use User\Api\UserApi;

/**
 * 后台用户控制器
 */
class ProjectController extends AdminController {
	
	public function _initialize(){

	    //风格分类
        $this->assign('style_list',getCategorySon('category',14));
        //户型分类
        $this->assign('house_list',getCategorySon('category',15));
        //项目工序
        $this->assign('gongxu_list',getCategorySon('category',20));
        //用户分组
        $where['bhy_userfz.status'] = array('eq',1);
        $userfz = M('userfz')->join('bhy_usermember as u on u.user_type=bhy_userfz.id')->where($where)->order('sort asc,id desc')->group('bhy_userfz.id')->field('bhy_userfz.*')->select();
        foreach ($userfz as $ke=>$ve){
            $whe['status']      = array('eq',1);
            $whe['check_status'] = array('eq',1);
            $whe['user_type']    = array('eq',$ve['id']);
            $userfz[$ke]['son_list'] = M('usermember')->where($whe)->order('id desc')->select();
        }
        $this->assign('userfz',$userfz);

		parent::_initialize();
	}



    public function index(){

		$get = $_GET;
		if($get['title']!=''){
			$where['title|address'] = array('like','%'.$get['title'].'%');
		}
		$times = timeCondition($get['start_time'],$get['end_time']);
		if($times!=0){
            $where['create_time'] = $times;
        }
        $where['status'] = array('gt',-1);
		//分页
        $listsCount = M('project')->where($where)->count();
        $Page       = new \Think\Page($listsCount,18);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出

	    $lists = M('project')->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach ($lists as $ks=>$vs){
            $lists[$ks]['jindu'] = gongxuJindu($vs['id']);
        }
		$this->assign('list',$lists);
        $this->assign('_page',$show);
		$this->display();
    }
	
	//编辑
	public function edit(){
		$id = I('request.id');
		if(IS_POST){
			$news = D('Project');
		    if($news->create()){
                $post = $_POST;
                if(empty($_POST['person'])){
                    $this->error('请选择关联人物！');
                }
                $info = M('project')->find($post['id']);
                $rw1 = explode(',',$info['person_id']);
                $rw2 = $_POST['person'];
                $crty = array_merge(array_diff($rw1,$rw2),array_diff($rw2,$rw1));

                //查询工序是否有变化
                $gx1 = $post['gongxu_id'];  $gx2 = gongxu($post['id']);
                $gxarr = array_merge(array_diff($gx1,$gx2),array_diff($gx2,$gx1));
                $gxarr2 = array_intersect($gx1,$gx2);
                $ertyu = $this->editGongxu($gxarr,$post,$gxarr2);
                if(!$ertyu){
                    $this->error('修改失败！');
                }

                $post['person_id']   = implode(',',$_POST['person']);
                $post['update_time'] = time();
                if(empty($crty)){
                    //人物未变化
                    $resu = M('project')->save($post);
                    if($resu){
                        $this->success('修改成功！',U('project/index'));
                    }else{
                        $this->error('修改失败！');
                    }
                }else{
                    //人物有变化的情况
                    $project = M('project');
                    $person = M('project_person');
                    $project->startTrans();  $person->startTrans(); //开启事物
                    $resu = $project->save($post);

                    $ii = 0;
                    $iii = 0;
                    foreach ($crty as $ks=>$vs){
                        $ttyy['project_id'] = array('eq',$post['id']);
                        $ttyy['uid'] = array('eq',$vs);
                        $ert = M('project_person')->where($ttyy)->find();
                        if(!empty($ert)){
                            $dats[$iii] = $ert['id'];
                            $iii++;
                        }else{
                            $dat[$ii]['project_id']  = $post['id'];
                            $dat[$ii]['uid']         = $vs;
                            $dat[$ii]['create_time'] = time();
                            $ii++;
                        }
                    }
                    if(!empty($dats)){
                        $whddt['id'] = array('in',implode(',',$dats));
                        $resy = $person->where($whddt)->delete();
                    }
                    if(!empty($dat)){
                        $resy = $person->addAll($dat);
                    }

                    if($resu&&$resy){
                        $project->commit();$person->commit();
                        $this->success('编辑成功！',U('project/index'));
                    }else{
                        $project->rollback();$person->rollback();
                        $this->error('编辑失败！');
                    }

                }

			}else{
				$this->error($news->getError());
			}
		}else{
			$vo = M('project')->find($id);
			$vo['person_id'] = explode(',',$vo['person_id']);
			$this->assign('vo',$vo);

            $gongxu_list = getCategorySon('category',20);
            foreach ($gongxu_list as $ks=>$vs){
                $whert['project_id'] = array('eq',$id);
                $whert['status'] = array('eq',1);
                $whert['gongxu_id'] = array('eq',$vs['id']);
                $gongxu_list[$ks]['son'] = M('project_date')->where($whert)->field('gongxu_id,order_time,gxsort')->find();
            }

            $this->assign('gongxu_list',$gongxu_list);
			$this->display();
		}
		
	}
	
	//新增
	public function add(){
		if(IS_POST){
            $news = D('Project');
		    if($news->create()){
		        $post = $_POST;
		        if(empty($_POST['person'])){
                    $this->error('请选择关联人物！');
                }
                if(empty($_POST['gongxu_id'])){
                    $this->error('请选择项目工序！');
                }
                $project = M('project');
                $person = M('project_person');
                $xmdate = M('project_date');
                $project->startTrans();  $person->startTrans(); $xmdate->startTrans();//开启事物

                $post['person_id']   = implode(',',$_POST['person']);
                $post['create_time'] = time();
                $post['mid']         = is_login();
				$resu = $project->add($post);

				//添加人物关联表
                foreach ($_POST['person'] as $ke=>$ve){
                    $data[$ke]['project_id'] = $resu;
                    $data[$ke]['uid']        = $ve;
                    $data[$ke]['create_time']= time();
                }
                $resu2 = $person->addAll($data);

                //添加工序关联
                $data3 = $this->xmGongxu($_POST,$resu);
                $resu3 = $xmdate->addAll($data3);

				if($resu&&$resu2&&$resu3){
                    $project->commit();$person->commit();$xmdate->commit();
					$this->success('新增成功！',U('project/index'));
				}else{
                    $project->rollback();$person->rollback();$xmdate->rollback();
					$this->error('新增失败！');
				}
			}else{
				$this->error($news->getError());
			}
		}else{
			$this->display();
		}
	}

	//项目工序
    public function xmGongxu($post,$project_id){
        foreach ($post['gongxu_id'] as $kh=>$vh){
            $data3[$kh]['gongxu_id'] = $vh;
            $data3[$kh]['project_id'] = $project_id;
            $data3[$kh]['gxsort'] = intval($post['gxsort'.$vh])>0?intval($post['gxsort'.$vh]):0;
            if($post['order_time'.$vh]!=''){
                $data3[$kh]['order_time'] = strtotime($post['order_time'.$vh]);
            }else{
                $data3[$kh]['order_time'] = 0;
            }
        }
        return $data3;
    }

    //编辑项目工序
    public function editGongxu($gxarr,$post,$gxarr2){

        if(empty($gxarr)){

            $iij=0;
            foreach (gongxuId($post['id']) as $kh=>$vh){
                $stuid[$iij] = $vh['id'];
                $dagh[$iij]['update_time'] = time();
                $dagh[$iij]['gxsort']      = $post['gxsort'.$vh['gongxu_id']];
                $dagh[$iij]['order_time']  = $post['order_time'.$vh['gongxu_id']]!=''?strtotime($post['order_time'.$vh['gongxu_id']]):0;
                $iij++;
            }

            $wherty['ID'] = $stuid;
            $resdf = saveAll($wherty,$dagh,'project_date');
        }else{
            //编辑原有的
            $iij=0;

            foreach (gongxuOne($post['id'],implode(',',$gxarr2),2) as $kh=>$vh){
                $stuid[$iij] = $vh['id'];
                $dagh[$iij]['update_time'] = time();
                $dagh[$iij]['gxsort']      = $post['gxsort'.$vh['gongxu_id']];
                $dagh[$iij]['order_time']  = $post['order_time'.$vh['gongxu_id']]!=''?strtotime($post['order_time'.$vh['gongxu_id']]):0;
                $iij++;
            }

            $wherty['ID'] = $stuid;
            $resdf = saveAll($wherty,$dagh,'project_date');
            //新增新的和删除取消的
            $ii = 0;
            $iii = 0;
            foreach ($gxarr as $ks=>$vs){
                $ttyy['project_id'] = array('eq',$post['id']);
                $ttyy['gongxu_id'] = array('eq',$vs);
                $ert = M('project_date')->where($ttyy)->find();
                if(!empty($ert)){
                    $dats[$iii] = $ert['id'];
                    $iii++;
                }else{
                    $dat[$ii]['project_id']  = $post['id'];
                    $dat[$ii]['gongxu_id']   = $vs;
                    $dat[$ii]['gxsort']      = $post['gxsort'.$vs];
                    $dat[$ii]['create_time'] = time();
                    $dat[$ii]['order_time']  = $post['order_time'.$vs]!=''?strtotime($post['order_time'.$vs]):0;
                    $ii++;
                }
            }

            if(!empty($dats)){
                $whddt['id'] = array('in',implode(',',$dats));
                $resdf = M('project_date')->where($whddt)->delete();
            }
            if(!empty($dat)){
                $resdf = M('project_date')->addAll($dat);
            }
        }

        if($resdf){
            return true;
        }else{
            return false;
        }

    }


     //删除
	public function del(){
		$id = I('request.id');

		if($id>0){
		  $lists = M('project')->where('id='.$id)->delete();
		  if($lists){
			  $this->success('删除成功');
		  }
		}else{
				$this->error('参数错误');
		}
		$this->display();
	}

	//删除所有
    public function forverdel(){
	    $pt = $_REQUEST;
	    if($pt['method']=='deleteUser'){
            $where['id'] = array('in',implode(',',$pt['id']));
            $res = M('project')->where($where)->delete();
            if($res){
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
    }


    //图集
    public function alatsList(){
        if(IS_POST){
            //p($_POST);
            $data['id'] = $_POST['id'];
            $data['imgarr'] = $_POST['pics'];
            $data['update_time'] = time();
            $vo = M('project')->save($data);
            if($vo){
                $this->ajaxReturn('200');
            }else{
                $this->ajaxReturn('201');
            }
        }else{

            $this -> assign('get',$_GET);
            $user = M('project')->find($_GET['id']);
            if(!empty($user['imgarr'])){
                //查询所属图集
                $at['id'] = array('in',$user['imgarr']);
                $at['status'] = array('eq',1);
                $picture = M('picture')->where($at)->select();
                //echo M('picture')->getLastSql();
                $this -> assign('picture',$picture);
            }
            $this -> assign('user',$user);
            $this -> display();
        }
    }

    //项目签到二维码
    public function project_ewm(){
        $pt = $_REQUEST;
        $path    = 'Uploads/Qrcode/'.date('Ymd').'/';
        $imgname = date('YmdHis').'_'.$pt['id'];
        $url     = C('WEB_SITE_URL').'/App/Public/user_sign?ewm=1&id='.$pt['id'];
        $this->qrcode($url,$path,$imgname);
        //存入二维码路径
        $arre['ewm_url'] = '/'.$path.$imgname.'.png';
        $ert = M('project')->where('id='.$pt['id'])->save($arre);
        if($ert){
            $this->success('二维码已生成');
        }else{
            $this->error('二维码生成失败');
        }
    }
//生成二维码
    public function qrcode($data,$path,$imgname,$level=3,$size=4){
        Vendor('Phpqrcode.phpqrcode');
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 10;
        if(!file_exists($path))
        {
            mkdir($path, 0700);
        }
        //  生成的文件名
        $fileName = $path.$imgname.'.png';
        ob_end_clean();//清空缓冲区
        $object = new \QRcode();
        $object->png($data,$fileName,$level, $size);
    }

//项目进度
public function evolve(){
    $group = get_user_group();
    $this->assign('group',$group);
    if(IS_POST){
        $post = $_POST;

        if($group==7){
            if(empty($post['gongxu_id'])){
                $this->error('请选择已完工的工序！'); exit;
            }else{
                if(count($post['gongxu_id'])>1){
                    $this->error('只能选择一个工序！'); exit;
                }else{
                    $vot = M('project_date')->find($post['gongxu_id'][0]);
                    $whe['gxsort']     = array('lt',$vot['gxsort']);
                    $whe['project_id'] = array('eq',$post['id']);
                    $vott = M('project_date')->where($whe)->order('gxsort desc')->find();
                    if(!empty($vott)){
                        if($vott['end_status']!=1){
                            $this->error('上一个工序没有完成，不能选择当前工序！'); exit;
                        }
                    }

                    $endtime = trim($post['end_time'.$post['gongxu_id'][0]]);
                    if($endtime==''){
                        $this->error('请选择结束日期！'); exit;
                    }
                    if(strtotime($endtime)>strtotime(date('Y-m-d'))){
                        $this->error('结束日期不能大于当前日期！'); exit;
                    }
                    if($vot['order_time']<strtotime($endtime)){
                        $this->error('结束日期已经大于预计完工日期，请联系超级管理员！'); exit;
                    }
                    //更新信息
                    $dagh['update_time'] = time();
                    $dagh['end_status']  = 1;
                    $dagh['end_time']    = strtotime($endtime);
                    $dagh['id']          = $post['gongxu_id'][0];
                    $resdf = M('project_date')->save($dagh);
                }
            }
        }else{
            $iij=0;
            foreach ($post['gongxu_id'] as $kh=>$vh){
                if($post['end_time'.$vh]==''){
                    $this->error('已完工的工序，请填写实际完工日期'); exit;
                }else{
                    if(strtotime($post['end_time'.$vh])>strtotime(date('Y-m-d'))){
                        $this->error('结束日期不能大于当前日期！'); exit;
                    }
                    $stuid[$iij] = $vh;
                    $dagh[$iij]['update_time'] = time();
                    $dagh[$iij]['end_status']  = 1;
                    $dagh[$iij]['end_time']    = strtotime($post['end_time'.$vh]);
                    $iij++;
                }

            }
            $wherty['ID'] = $stuid;
            $resdf = saveAll($wherty,$dagh,'project_date');
        }

        if($resdf){
            $this->success('更新成功');
        }else{
            $this->success('更新失败');
        }

    }else{
        $get = $_GET;
        $this->assign('get',$get);
        $whert['p.project_id'] = array('eq',$get['id']);
        $whert['p.status']    = array('eq',1);
        $gongxu_list = M('category')->join('bhy_project_date as p on p.gongxu_id=bhy_category.id')->where($whert)->field('bhy_category.title,p.*')->order('p.gxsort asc')->select();
        $this->assign('gongxu_list',$gongxu_list);
        // p($list);
        $this->display();
    }
}





}
